<?php

namespace app\api\controller\v1;
include_once APP_PATH . 'api/common.php';
use app\common\controller\Api;
use think\Db;
use think\Request;

class Curriculum extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function getDashboard(Request $request)
    {
        $user = $this->auth->getUser();
        if (!$user || !isset($user['uid'])) {
            return json(['code' => 0, 'msg' => '未登录', 'data' => null]);
        }

        file_put_contents($_SERVER["DOCUMENT_ROOT"]."/../"."log_curriculum.txt", date('Y-m-d H:i:s')." getDashboard uid=".$user['uid']."\n", FILE_APPEND);

        $uid = $user['uid'];

        $classes = Db::name('eb_apply_form_item')
            ->alias('f')
            ->join('fa_order o', 'f.order_id = o.id', 'left')
            ->join('eb_classes c', 'f.classes_type=1 and f.classes_id = c.id', 'left')
            ->join('fa_ocation_class c2', 'f.classes_type=2 and f.classes_id = c2.id', 'left')
            ->join('fa_subject_lv s', 'f.classes_type=1 and c.subject_lv = s.id', 'left')
            ->join('fa_community_course_config s2', 'f.classes_type=2 and c2.subject_lv = s2.id', 'left')
            ->join('eb_school sch', 'sch.id = c.school_id', 'left')
            ->join('eb_school sch2', 'sch2.id = c2.school_id', 'left')
            ->where('f.user_id', $uid)
            ->where('f.pay_status', 1)
            ->field("f.classes_id,f.classes_type,COALESCE(c.name,c2.name) as class_name,COALESCE(s.name,s2.name) as subject_name,COALESCE(sch.name,sch2.name) as school_name,COALESCE(c.school_id,c2.school_id) as school_id")
            ->group('f.classes_id')
            ->limit(20)
            ->select();

        $mapIcons = function($subject){
            $m = [
                '书法' => '✍️',
                '声乐' => '🎵',
                '美术' => '🎨',
                '舞蹈' => '💃'
            ];
            foreach ($m as $k=>$v) { if ($subject && mb_strpos($subject, $k) !== false) return $v; }
            return '📘';
        };

        $classTabs = [];
        $nowTs = time();
        foreach ($classes as $row) {
            $cid = intval($row['classes_id']);
            $ctype = intval($row['classes_type']);
            $upcoming = Db::name('fa_course_table_autoplan')
                ->where('classes_id', $cid)
                ->where('table_type', $ctype)
                ->where('status', 1)
                ->whereRaw("CONCAT(date,' ', start_time, ':00') >= NOW()")
                ->order('date asc, start_time asc')
                ->field('date,start_time,end_time')
                ->find();
            $ongoing = Db::name('fa_course_table_autoplan')
                ->where('classes_id', $cid)
                ->where('table_type', $ctype)
                ->where('status', 1)
                ->whereRaw("CONCAT(date,' ', start_time, ':00') <= NOW() AND CONCAT(date,' ', end_time, ':00') >= NOW()")
                ->order('date asc, start_time asc')
                ->field('date,start_time,end_time')
                ->find();
            $timeUntil = 999999999;
            $nextLabel = '';
            if ($ongoing) {
                $timeUntil = 0;
                $dt = $ongoing['date']?:'';
                $st = $ongoing['start_time']?:'';
                $et = $ongoing['end_time']?:'';
                $nextLabel = ($dt?date('Y年m月d日', strtotime($dt)):'').($st||$et?(' '.trim($st).' - '.trim($et)):'');
            } elseif ($upcoming) {
                $dt = $upcoming['date']?:'';
                $st = $upcoming['start_time']?:'';
                $et = $upcoming['end_time']?:'';
                $startTs = ($dt && $st) ? strtotime($dt.' '.$st.':00') : 0;
                $timeUntil = $startTs>0 ? max(0, $startTs - $nowTs) : 999999999;
                $nextLabel = ($dt?date('Y年m月d日', strtotime($dt)):'').($st||$et?(' '.trim($st).' - '.trim($et)):'');
            }
            $classTabs[] = [
                'name' => $row['class_name']?:'未命名班级',
                'icon' => $mapIcons($row['subject_name']??''),
                'hasNotification' => false,
                'classes_id' => $row['classes_id'],
                'classes_type' => $row['classes_type'],
                'timeUntil' => $timeUntil,
                'nextTime' => $nextLabel
            ];
        }
        usort($classTabs, function($a, $b){
            $ta = isset($a['timeUntil']) ? intval($a['timeUntil']) : 999999999;
            $tb = isset($b['timeUntil']) ? intval($b['timeUntil']) : 999999999;
            if ($ta == $tb) return 0;
            return ($ta < $tb) ? -1 : 1;
        });

        $firstTab = isset($classTabs[0]) ? $classTabs[0] : null;
        $current = [
            'time' => '',
            'school' => '',
            'className' => $firstTab ? ($firstTab['name']?:'') : ''
        ];

        if ($firstTab) {
            $schedule = Db::name('fa_course_table_autoplan')
                ->where('classes_id', intval($firstTab['classes_id']))
                ->where('table_type', intval($firstTab['classes_type']))
                ->where('status', 1)
                ->order('date asc, start_time asc')
                ->limit(1)
                ->find();
            if ($schedule) {
                $st = isset($schedule['start_time']) ? $schedule['start_time'] : '';
                $et = isset($schedule['end_time']) ? $schedule['end_time'] : '';
                $dt = isset($schedule['date']) ? $schedule['date'] : '';
                $current['time'] = ($dt?date('Y年m月d日', strtotime($dt)):'').($st||$et?(' '.trim($st).' - '.trim($et)):'');
            }
            $sid = 0;
            if (intval($firstTab['classes_type']) === 1) {
                $sid = Db::name('eb_classes')->where('id', intval($firstTab['classes_id']))->value('school_id');
            } else {
                $sid = Db::name('fa_ocation_class')->where('id', intval($firstTab['classes_id']))->value('school_id');
            }
            if ($sid) {
                $sname = Db::name('eb_school')->where('id', $sid)->value('name');
                $current['school'] = $sname?:'';
            }
        }

        $classIds = array_map(function($r){ return intval($r['classes_id']); }, $classes);
        $history = [];
        if (!empty($classIds)) {
            $list = Db::name('fa_course_table_autoplan')
                ->where('classes_id', 'in', $classIds)
                ->order('date desc')
                ->limit(10)
                ->select();
            foreach ($list as $it) {
                $cinfo = Db::name('eb_classes')->where('id', $it['classes_id'])->field('name, school_id')->find();
                if (!$cinfo) {
                    $c2 = Db::name('fa_ocation_class')->where('id', $it['classes_id'])->field('name, school_id')->find();
                    $cinfo = $c2 ? $c2 : ['name'=>'', 'school_id'=>0];
                }
                $sname = '';
                if (!empty($cinfo['school_id'])) {
                    $schname = Db::name('eb_school')->where('id', $cinfo['school_id'])->value('name');
                    $sname = $schname?:'';
                }
                $history[] = [
                    'date' => isset($it['date']) ? date('Y年m月d日', strtotime($it['date'])) : '',
                    'time' => ((isset($it['start_time'])?$it['start_time']:'').' - '.(isset($it['end_time'])?$it['end_time']:'')),
                    'school' => $sname,
                    'className' => $cinfo['name']?:'',
                    'status' => 'completed'
                ];
            }
        }

        $courseStatus = [
            ['name' => '准备上课', 'icon' => '⏰', 'active' => true],
            ['name' => '上课进行中', 'icon' => '📚', 'active' => false],
            ['name' => '课程已结束', 'icon' => '✅', 'active' => false]
        ];

        return json([
            'code' => 200,
            'msg' => 'ok',
            'data' => [
                'classTabs' => $classTabs,
                'courseStatus' => $courseStatus,
                'currentCourseInfo' => [
                    ['label' => '时间', 'value' => $current['time'], 'icon' => '🕐'],
                    ['label' => '学校', 'value' => $current['school'], 'icon' => '🏫'],
                    ['label' => '班级', 'value' => $current['className'], 'icon' => '👥']
                ],
                'courseHistory' => $history
            ]
        ]);
    }

    public function getClassDashboard(Request $request)
    {
        $user = $this->auth->getUser();
        if (!$user || !isset($user['uid'])) {
            return json(['code' => 0, 'msg' => '未登录', 'data' => null]);
        }

        $classes_id = intval($request->get('classes_id', 0));
        $classes_type = intval($request->get('classes_type', 1));
        if ($classes_id <= 0) {
            return json(['code' => 0, 'msg' => '参数错误', 'data' => null]);
        }

        $base = Db::name('fa_course_table_autoplan')
            ->alias('t')
            ->join('eb_school sch', 'sch.id=t.school_id', 'left')
            ->join('eb_classes c1', 't.table_type=1 and c1.id=t.classes_id', 'left')
            ->join('fa_ocation_class oc', 't.table_type=2 and oc.id=t.classes_id', 'left')
            ->where('t.status', 1)
            ->where('t.classes_id', $classes_id)
            ->where('t.table_type', $classes_type);

        $upcoming = clone $base;
        $schedule = $upcoming
            ->whereRaw("CONCAT(t.date,' ', t.start_time, ':00') >= NOW()")
            ->order('t.date asc, t.start_time asc')
            ->field("t.date,t.start_time,t.end_time,sch.name as school_name,COALESCE(c1.name,oc.name) as class_name")
            ->find();

        if (!$schedule) {
            $latest = clone $base;
            $schedule = $latest
                ->order('t.date desc, t.end_time desc')
                ->field("t.date,t.start_time,t.end_time,sch.name as school_name,COALESCE(c1.name,oc.name) as class_name")
                ->find();
        }

        $currentTime = '';
        $schoolName = '';
        $className = '';
        $timeLeft = '';

        if ($schedule) {
            $dt = isset($schedule['date']) ? $schedule['date'] : '';
            $st = isset($schedule['start_time']) ? $schedule['start_time'] : '';
            $et = isset($schedule['end_time']) ? $schedule['end_time'] : '';
            $currentTime = ($dt ? date('Y年m月d日', strtotime($dt)) : '') . ($st || $et ? (' ' . trim($st) . ' - ' . trim($et)) : '');
            $schoolName = $schedule['school_name'] ?: '';
            $className = $schedule['class_name'] ?: '';

            $startTs = ($dt && $st) ? strtotime($dt . ' ' . $st . ':00') : 0;
            $endTs = ($dt && $et) ? strtotime($dt . ' ' . $et . ':00') : 0;
            $now = time();
            if ($startTs > $now) {
                $diff = $startTs - $now;
                if ($diff >= 86400) {
                    $d = intval($diff / 86400);
                    $timeLeft = $d . '天';
                } else {
                    $h = intval($diff / 3600);
                    $m = intval(($diff % 3600) / 60);
                    $timeLeft = ($h > 0 ? ($h . '小时') : '') . ($m > 0 ? ($m . '分钟') : ($h <= 0 ? '不到1分钟' : ''));
                }
            } elseif ($startTs <= $now && $endTs >= $now) {
                $timeLeft = '正在进行';
            } else {
                $timeLeft = '已结束';
            }
        }

        $historyRows = $base
            ->order('t.date desc, t.start_time desc')
            ->limit(10)
            ->field("t.date,t.start_time,t.end_time,sch.name as school_name,COALESCE(c1.name,oc.name) as class_name")
            ->select();

        $history = [];
        foreach ($historyRows as $it) {
            $dt = isset($it['date']) ? $it['date'] : '';
            $st = isset($it['start_time']) ? $it['start_time'] : '';
            $et = isset($it['end_time']) ? $it['end_time'] : '';
            $startTs = ($dt && $st) ? strtotime($dt . ' ' . $st . ':00') : 0;
            $endTs = ($dt && $et) ? strtotime($dt . ' ' . $et . ':00') : 0;
            $now = time();
            $status = 'upcoming';
            if ($endTs < $now) {
                $status = 'completed';
            } elseif ($startTs <= $now && $endTs >= $now) {
                $status = 'ongoing';
            }
            $statusTextMap = [
                'upcoming' => '即将开始',
                'ongoing' => '正在进行',
                'completed' => '已完成'
            ];
            $history[] = [
                'date' => $dt ? date('Y年m月d日', strtotime($dt)) : '',
                'time' => ($st ? $st : '') . ' - ' . ($et ? $et : ''),
                'school' => isset($it['school_name']) ? $it['school_name'] : '',
                'className' => isset($it['class_name']) ? $it['class_name'] : '',
                'status' => $status,
                'status_text' => isset($statusTextMap[$status]) ? $statusTextMap[$status] : $status
            ];
        }

        return json([
            'code' => 200,
            'msg' => 'ok',
            'data' => [
                'currentCourseInfo' => [
                    ['label' => '时间', 'value' => $currentTime, 'icon' => '🕐'],
                    ['label' => '学校', 'value' => $schoolName, 'icon' => '🏫'],
                    ['label' => '班级', 'value' => $className, 'icon' => '👥']
                ],
                'courseHistory' => $history,
                'timeLeft' => $timeLeft
            ]
        ]);
    }
}